package com.keldian.www.sunlight;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class WeatherDataParser {

	/**
	 * Given a string of the form returned by the api call:
	 * http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7 
	 * retrieve the maximum temperature for the day indicated by dayIndex
	 * (Note: 0-indexed, so 0 would refer to the first day).
	 */
	public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
		throws JSONException {
		// TODO: add parsing code here
		if(weatherJsonStr == null){
			return -1;
		}else{
			JSONObject weatherDataObject = new JSONObject(weatherJsonStr);
			JSONArray weatherArray =  weatherDataObject.getJSONArray("list");

			if(weatherArray.length() != 0){
				//将获取到weatherData中找到的集合数据转化为数组
				JSONArray weatherDataArray = null;
				if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
					weatherDataArray = new JSONArray(weatherArray);
				}
				if(!weatherDataArray.isNull(dayIndex)){
					//获取dayIndex指定天气的数据
					JSONObject dayData = weatherDataArray.getJSONObject(dayIndex);
					//然后获取temp温度
					JSONObject tempObject = dayData.getJSONObject("temp");
					double tempMax = tempObject.getDouble("max");
					System.out.println(tempMax);
					return tempMax;
				}
			}

		}
		
		return -1;
	}

}